package woaini.wind.bot.listenner;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import woaini.wind.bot.chat.impl.CozeChatter;
import woaini.wind.bot.chat.stream.WindChatStream;
import woaini.wind.bot.core.chat.ChatEvent;
import woaini.wind.bot.core.session.Session;
import woaini.wind.bot.chat.impl.GptChatter;

/**
 * 只会收到 私聊消息 而且是主账户发过来的
 *
 * @see MessageListener
 * @author yefeng {@date 2024-09-03 16:42:27}
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MessageListener {

  private final GptChatter chatter;
  private final CozeChatter cozeChatter;

  @EventListener
  public void onMessage(ChatEvent chatEvent) {
    Session session = chatEvent.getSession();
    String actualText = session.getActualText();
    String name = session.getBind().getBotUser().getName();
    if (StrUtil.isEmpty(name)) {
      name = "陌生人";
    }
    try {
      WindChatStream windChatStream = new WindChatStream();
      cozeChatter.streamChat(windChatStream, String.valueOf(session.getUserId()), name, actualText);
      while (windChatStream.hasNext()) {
        String chat = windChatStream.getMessage();
        if (StrUtil.isNotEmpty(chat)){
          session.replyMessage(chat);
        }
      }
    } catch (Exception e) {
      log.error("cozeChatter error", e);
      session.replyMessage("请求异常!!!");
    }
  }
}
